package cn.quang.search.toolkit.provider.entity;

import java.util.HashMap;
import java.util.Map;

public class Context {

    private Map<String, Object> contextMap = new HashMap<>();

    public void set(String field, Object value){
        this.contextMap.put(field, value);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String field, Class<T> clazz){
        Object o = contextMap.get(field);
        if(o == null){
            return null;
        }
        if(clazz.isInstance(o)){
            return (T) o;
        }
        throw new IllegalStateException("数据类型与提供的类[" + clazz.getName() + "]类型不符。");
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String field, Class<T> clazz, T defaultValue){
        Object o = contextMap.get(field);
        if(o == null){
            return defaultValue;
        }
        if(clazz.isInstance(o)){
            return (T) o;
        }
        throw new IllegalStateException("数据类型与提供的类[" + clazz.getName() + "]类型不符。");
    }

    public boolean exists(String field){
        return contextMap.containsKey(field);
    }

    public Map<String, Object> getContextMap() {
        return contextMap;
    }

    public void setContextMap(Map<String, Object> contextMap) {
        this.contextMap = contextMap;
    }
}
